package com.example.tbsdemo;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;

import java.io.File;

public class DownLoadUtils {
    public static void downLoadDatabase(String Url, final CallBack callBack) {

//        String strDBPath3 = context.getExternalFilesDir(null) + "/TIS- Smarthome/"+"download/";//下载路径
        String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/007/";//下载路径

        OkGo.<File>get(Url)
                /*.tag(this)
                .headers("header1", "headerValue1")
                .params("db3", String.valueOf(new File(strDBPath)))
                    .params("securityCode",pblvariables.security_code)*//*验证码*//*
                    .params("Remark",choose)*//*数据库名称*/
                .execute(new FileCallback(filepath,getFileName(Url)) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<File> response) {
                        Log.i("AACC","下载成功1 " + response.body());
                        if (callBack!=null)callBack.FileCallBack(response.body());
                    }   //指定下载的路径  下载文件名


                    @Override
                    public void onError(com.lzy.okgo.model.Response<File> response) {
                        super.onError(response);
                        Log.i("AACC","下载失败1 " + response.body());
                    }
                });
    }

    public interface CallBack{
        public void FileCallBack(File file);
    }

    /***
     * 根据链接获取文件名（带类型的），具有唯一性
     *
     * @param url
     * @return
     */
    private static String getFileName(String url) {
        String fileName = Md5Tool.hashKey(url) + "." + getFileType(url);
        return fileName;
    }

    /***
     * 获取文件类型
     *
     * @param paramString
     * @return
     */
    private static String getFileType(String paramString) {
        String str = "";

        if (TextUtils.isEmpty(paramString)) {

            return str;
        }
//        TLog.d(TAG,"paramString:"+paramString);
        int i = paramString.lastIndexOf('.');
        if (i <= -1) {

            return str;
        }
        str = paramString.substring(i + 1);

        return str;
    }
}